import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
import type { IIndex } from '@/types';
import { showConfirmDialog } from 'vant';
import 'vant/lib/dialog/index.css';

export interface ICart extends IIndex {
  title: string;
  desc?: string;
  num: number;
  price: number;
  check: boolean;
  thumb: string;
}

export const useCartStore = defineStore(
  'pinia',
  () => {
    // 商品列表
    const list = ref<ICart[]>([
      {
        title: '商品标题1',
        desc: '描述信息1',
        num: 1,
        price: 99,
        check: true,
        thumb: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      },
      {
        title: '商品标题2',
        desc: '描述信息2',
        num: 2,
        price: 189.2,
        check: true,
        thumb: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      },
    ]);

    // 计算选中商品总数
    const totalCount = computed(() => {
      return list.value
        .filter((item) => item.check)
        .reduce((pre, cur) => {
          return pre + cur.num;
        }, 0);
    });

    // 计算选中商品总价
    const totalPrice = computed(() => {
      return list.value
        .filter((item) => item.check)
        .reduce((pre, cur) => {
          return pre + cur.num * cur.price;
        }, 0);
    });

    // 添加商品并判重
    const push = (cart: ICart) => {
      const index = list.value.findIndex((item) => item.id === cart.id);
      if (index == -1) {
        cart.num = 1;
        cart.check = false;
        list.value.push(cart);
      } else {
        list.value[index].num++;
      }
    };

    // 删除指定索引项
    const delIndex = (index: number) => {
      if (index >= 0 && index < list.value.length) {
        showConfirmDialog({
          title: '温馨提示',
          message: '确定要删除？',
          width: '80vw',
        })
          .then(() => {
            list.value.splice(index, 1);
          })
          .catch((err) => {
            console.log('取消删除', err);
          });
      }
    };

    // 删除选中项
    const delChecked = () => {
      showConfirmDialog({
        title: '温馨提示',
        message: '确定要删除选中项？',
        width: '80vw',
      })
        .then(() => {
          list.value = list.value.filter((item) => !item.check);
        })
        .catch((err) => {
          console.log('取消删除', err);
        });
    };

    // 全选状态
    const checkAllState = computed(() => {
      return list.value.every((item) => item.check);
    });

    // 切换全选状态
    const toggleCheckAllState = () => {
      const check = checkAllState.value;
      list.value.forEach((item) => {
        item.check = !check;
      });
    };

    return { list, totalCount, totalPrice, push, delIndex, delChecked, checkAllState, toggleCheckAllState };
  },
  { persist: true },
);
